//
//  UITextView+LKPlaceholder.m
//  DlfcAgent
//
//  Created by 1em0nsOft on 2017/3/13.
//  Copyright © 2017年 Lemonsoft. All rights reserved.
//

#import "UITextView+LKPlaceholder.h"
#import <objc/runtime.h>

static const void *placeholderKey = &placeholderKey;
static const void *placeholderLabelKey = &placeholderLabelKey;

@interface UITextView (LKPlaceHolder)

@property UILabel *placeholderLabel;

@end

@implementation UITextView (LKPlaceholder)

- (void)setPlaceholder:(NSString *)placeholder{
    objc_setAssociatedObject(self, placeholderKey, placeholder, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (!self.placeholderLabel){
        CGSize placeholderSize = [placeholder sizeWithAttributes: @{NSFontAttributeName: self.font}];
        self.placeholderLabel = [[UILabel alloc] initWithFrame: CGRectMake(5, 8, placeholderSize.width, placeholderSize.height)];
        [self addSubview: self.placeholderLabel];
        self.placeholderLabel.text = placeholder;
        self.placeholderLabel.font = self.font;
        self.placeholderLabel.textColor = [UIColor lightGrayColor];
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(textChange) name: UITextViewTextDidChangeNotification object: nil];
        if (self.text.length > 0) {
                    self.placeholderLabel.text = @"";
        }
    }
}

- (void)setPlaceholderLabel:(UILabel *)placeholderLabel{
    objc_setAssociatedObject(self, placeholderLabelKey, placeholderLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UILabel *)placeholderLabel{
    return objc_getAssociatedObject(self, placeholderLabelKey);
}

- (NSString *)placeholder{
    return objc_getAssociatedObject(self, placeholderKey);
}

- (void)textChange{
    self.placeholderLabel.hidden = !([self.text isEqualToString: @""] && self.placeholderLabel);
}

@end
